package com.blank.shop.security.handler;

import com.blank.shop.security.config.BlankShopProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * <br/>Date 2021/9/9
 * <br/>Time 23:54:56
 *
 * @author _blank
 */
@Slf4j
@Component
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Resource
    private ObjectMapper jacksonObjectMapper;

    private final BlankShopProperties blankShopProperties;

    public MyAuthenticationSuccessHandler(BlankShopProperties blankShopProperties) {
        this.blankShopProperties = blankShopProperties;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登录成功！");

        if (Objects.equals(BlankShopProperties.LoginType.JSON, this.blankShopProperties.getBrowser().getLoginType())) {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write(this.jacksonObjectMapper.writeValueAsString(authentication));
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }


    }

}
